/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.ubhave.sensormanager.ability;

import com.ubhave.sensormanager.ESException;
import com.ubhave.sensormanager.ESSensorManager;
import com.ubhave.sensormanager.ResourceTable;
import com.ubhave.sensormanager.SensorDataListener;
import com.ubhave.sensormanager.data.SensorData;
import com.ubhave.sensormanager.data.push.BatteryData;
import com.ubhave.sensormanager.data.push.ConnectionStateData;
import com.ubhave.sensormanager.sensors.SensorUtils;
import com.ubhave.sensormanager.utils.IPUtil;
import com.ubhave.sensormanager.utils.LogUtil;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.net.NetHandle;
import ohos.utils.PacMap;
import ohos.utils.Sequenceable;
import ohos.wifi.WifiLinkedInfo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

public class ConnectionStateAbility extends Ability implements SensorDataListener, Component.ClickedListener {

    private int subscriptionId;
    private ESSensorManager sensorManager;

    private Text text_data;
    private SensorData mSensorData;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_connection_state);
        text_data = (Text) findComponentById(ResourceTable.Id_connection_state_data);
        findComponentById(ResourceTable.Id_start_btn).setClickedListener(this::onClick);
        findComponentById(ResourceTable.Id_stop_btn).setClickedListener(this::onClick);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (sensorManager != null) {
            try {
                sensorManager.unsubscribeFromSensorData(subscriptionId);
            } catch (ESException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_start_btn:
                LogUtil.loge("===Id_start_btn");
                try {
                    sensorManager = ESSensorManager.getSensorManager(getContext());
                    subscriptionId = sensorManager.subscribeToSensorData(SensorUtils.SENSOR_TYPE_CONNECTION_STATE, this);
                } catch (ESException e) {
                    e.printStackTrace();
                }
                break;
            case ResourceTable.Id_stop_btn:
                LogUtil.loge("===Id_stop_btn");
                if (sensorManager != null) {
                    try {
                        sensorManager.unsubscribeFromSensorData(subscriptionId);
                    } catch (ESException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    @Override
    public void onDataSensed(SensorData data) {
        LogUtil.loge("===onDataSensed: " + data.toString());

        mSensorData = data;
        parseData(mSensorData);

    }

    private void parseData(SensorData data) {
        if(!(data instanceof ConnectionStateData)) {
            return;
        }
        ConnectionStateData connectionStateData = (ConnectionStateData) data;
        StringBuffer buffer = new StringBuffer();
        String ssid = connectionStateData.getSSID();

        WifiLinkedInfo wifiInfo = connectionStateData.getWifiInfo();
        String connState = wifiInfo.getConnState().name();

        buffer.append("当前连接状态信息: \n");

        long timestamp = connectionStateData.getTimestamp();
        Date date = new Date();
        date.setTime(timestamp);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String dateString = dateFormat.format(date);
        buffer.append("senseStartTime: ").append(dateString).append("\n");
        buffer.append("senseStartTimeMillis: ").append(timestamp).append("\n");

        buffer.append("ssid:").append(ssid).append("\n");
        buffer.append("bssid:").append(wifiInfo.getBssid()).append("\n");
        buffer.append("rssi:").append(wifiInfo.getRssi()).append("\n");
        buffer.append("band:").append(wifiInfo.getBand()).append("\n");
        buffer.append("连接状态:").append(connState).append("\n");
        buffer.append("物理地址:").append(wifiInfo.getMacAddress()).append("\n");
        buffer.append("连接速度:").append(wifiInfo.getLinkSpeed()).append("\n");
        buffer.append("Ip地址:").append(IPUtil.longToIP(wifiInfo.getIpAddress())).append("\n");
        text_data.setVisibility(Component.VISIBLE);
        text_data.setText(buffer.toString());
    }

    @Override
    public void onCrossingLowBatteryThreshold(boolean isBelowThreshold) {
        LogUtil.loge("===onCrossingLowBatteryThreshold: " + isBelowThreshold);
    }
    @Override
    public void onRestoreAbilityState(PacMap inState) {
        super.onRestoreAbilityState(inState);
        Optional<Sequenceable> sensorDataOptional = inState.getSequenceable("sensorData");
        if(sensorDataOptional.isPresent()) {
            mSensorData = (SensorData) sensorDataOptional.get();
            parseData(mSensorData);
        }
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        super.onSaveAbilityState(outState);
        if(mSensorData != null) {
            outState.putSequenceableObject("sensorData", mSensorData);
        }
    }

}